package cn.ecsd.dao.impl;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import cn.ecsd.common.CommonDao;
import cn.ecsd.entity.SysEmployee;
import cn.ecsd.util.PageSupport;

//@Repository("commonDao")
public class CommonDaoHibeImp extends HibernateDaoSupport implements CommonDao {
	public CommonDaoHibeImp() {
	}

	/*
	 * @Autowired public CommonDaoHibeImp(@Qualifier("sessionFactory")
	 * SessionFactory sessionFactory) { this.setSessionFactory(sessionFactory);
	 * }
	 */

	/**
	 * 根据主键获得一条数据
	 */
	@Override
	public Object get(Class clazz, Serializable id) {
		// TODO Auto-generated method stub
		return super.getHibernateTemplate().get(clazz, id);
	}

	/**
	 * 添加数据到数据库
	 */
	@Override
	public Serializable add(Object o) {
		// TODO Auto-generated method stub
		return super.getHibernateTemplate().save(o);
	}

	/**
	 * 根据主键删除数据
	 */
	@Override
	public void del(Object entity) {
		super.getHibernateTemplate().delete(entity);;
	}

	/**
	 * 更新数据
	 */
	@Override
	public void update(Object o) {
		super.getHibernateTemplate().update(o);
	}

	/**
	 * 查询数据
	 */
	@Override
	public List search(String sql) {
		// TODO Auto-generated method stub
		return super.getHibernateTemplate().find(sql);
	}

	/**
	 * 实现分页查询获得数据集合
	 */
	@Override
	public List queryPage(final String sql, final PageSupport page) {
		return (List) this.getHibernateTemplate().execute(new HibernateCallback() {

			@Override
			public List doInHibernate(Session session) throws HibernateException, SQLException {
				Query query = session.createQuery(sql);
				query.setFirstResult((page.getCurrentPageNo()-1)*page.getPageSize());
				query.setMaxResults(page.getPageSize());
				return query.list();
			}
		});
	}

	/**
	 * 数据记录总数 获得
	 */
	@Override
	public int getCount(String sql) {
		Long count =  (Long) getHibernateTemplate().find(sql).listIterator().next();
		return count.intValue();
	}

}
